<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Generator 函数的异步应用 | Evan&#39;s blog</title>
    <meta name="generator" content="VuePress 1.9.5">
    <link rel="icon" href="/blog/img/favicon.ico">
    <meta name="description" content="web前端技术博客,专注web前端学习与总结。JavaScript,js,ES6,TypeScript,vue,React,python,css3,html5,Node,git,github等技术文章。">
    <meta name="keywords" content="前端博客,个人技术博客,前端,前端开发,前端框架,web前端,前端面试题,技术文档,学习,面试,JavaScript,js,ES6,TypeScript,vue,python,css3,html5,Node,git,github,markdown">
    <meta name="baidu-site-verification" content="7F55weZDDc">
    <meta name="theme-color" content="#11a8cd">
    
    <link rel="preload" href="/blog/assets/css/0.styles.5cae76fb.css" as="style"><link rel="preload" href="/blog/assets/js/app.aaf1b95a.js" as="script"><link rel="preload" href="/blog/assets/js/2.4e88da26.js" as="script"><link rel="preload" href="/blog/assets/js/102.c6fb27ad.js" as="script"><link rel="prefetch" href="/blog/assets/js/10.77cd5446.js"><link rel="prefetch" href="/blog/assets/js/100.a4b7c22a.js"><link rel="prefetch" href="/blog/assets/js/101.f10a486b.js"><link rel="prefetch" href="/blog/assets/js/103.6544c57a.js"><link rel="prefetch" href="/blog/assets/js/104.6da84eb0.js"><link rel="prefetch" href="/blog/assets/js/105.e98afb5b.js"><link rel="prefetch" href="/blog/assets/js/106.00c6a618.js"><link rel="prefetch" href="/blog/assets/js/107.3e384ab5.js"><link rel="prefetch" href="/blog/assets/js/108.cc8462f3.js"><link rel="prefetch" href="/blog/assets/js/109.efac7118.js"><link rel="prefetch" href="/blog/assets/js/11.0b77905f.js"><link rel="prefetch" href="/blog/assets/js/110.bfd96a59.js"><link rel="prefetch" href="/blog/assets/js/111.d67fb86c.js"><link rel="prefetch" href="/blog/assets/js/112.9ecfc68a.js"><link rel="prefetch" href="/blog/assets/js/113.dd57f9de.js"><link rel="prefetch" href="/blog/assets/js/114.a12ac3b9.js"><link rel="prefetch" href="/blog/assets/js/115.856e382b.js"><link rel="prefetch" href="/blog/assets/js/116.941afac4.js"><link rel="prefetch" href="/blog/assets/js/117.df53da43.js"><link rel="prefetch" href="/blog/assets/js/118.906f3d41.js"><link rel="prefetch" href="/blog/assets/js/119.33bd4cde.js"><link rel="prefetch" href="/blog/assets/js/12.6a1ae269.js"><link rel="prefetch" href="/blog/assets/js/120.c7d90a2a.js"><link rel="prefetch" href="/blog/assets/js/121.e9a583b9.js"><link rel="prefetch" href="/blog/assets/js/122.d2edbcb6.js"><link rel="prefetch" href="/blog/assets/js/123.1a632657.js"><link rel="prefetch" href="/blog/assets/js/124.2a2decb0.js"><link rel="prefetch" href="/blog/assets/js/125.f9344214.js"><link rel="prefetch" href="/blog/assets/js/126.90a937ca.js"><link rel="prefetch" href="/blog/assets/js/127.541a2bd8.js"><link rel="prefetch" href="/blog/assets/js/128.d197e7a9.js"><link rel="prefetch" href="/blog/assets/js/129.bd2b74bf.js"><link rel="prefetch" href="/blog/assets/js/13.a3d3aa42.js"><link rel="prefetch" href="/blog/assets/js/130.4555d2a9.js"><link rel="prefetch" href="/blog/assets/js/131.af4d4381.js"><link rel="prefetch" href="/blog/assets/js/132.15b408e6.js"><link rel="prefetch" href="/blog/assets/js/133.c6819d56.js"><link rel="prefetch" href="/blog/assets/js/134.2b49eb48.js"><link rel="prefetch" href="/blog/assets/js/135.7b5224d1.js"><link rel="prefetch" href="/blog/assets/js/136.e966c07b.js"><link rel="prefetch" href="/blog/assets/js/137.962a7287.js"><link rel="prefetch" href="/blog/assets/js/138.e4446fa5.js"><link rel="prefetch" href="/blog/assets/js/139.d0a5415a.js"><link rel="prefetch" href="/blog/assets/js/14.d68bef9a.js"><link rel="prefetch" href="/blog/assets/js/140.23d79a44.js"><link rel="prefetch" href="/blog/assets/js/141.e09939d0.js"><link rel="prefetch" href="/blog/assets/js/142.266a27e9.js"><link rel="prefetch" href="/blog/assets/js/143.ed3c54b1.js"><link rel="prefetch" href="/blog/assets/js/144.98c6792d.js"><link rel="prefetch" href="/blog/assets/js/145.a18f3f3f.js"><link rel="prefetch" href="/blog/assets/js/146.106bb541.js"><link rel="prefetch" href="/blog/assets/js/147.4b313651.js"><link rel="prefetch" href="/blog/assets/js/148.4a6ec42d.js"><link rel="prefetch" href="/blog/assets/js/149.9ec297ab.js"><link rel="prefetch" href="/blog/assets/js/15.81a99c55.js"><link rel="prefetch" href="/blog/assets/js/150.823ccad7.js"><link rel="prefetch" href="/blog/assets/js/151.1eee0fd4.js"><link rel="prefetch" href="/blog/assets/js/152.71ae0047.js"><link rel="prefetch" href="/blog/assets/js/153.63d5a471.js"><link rel="prefetch" href="/blog/assets/js/154.77169175.js"><link rel="prefetch" href="/blog/assets/js/155.c460c129.js"><link rel="prefetch" href="/blog/assets/js/156.793e4b57.js"><link rel="prefetch" href="/blog/assets/js/157.c9261336.js"><link rel="prefetch" href="/blog/assets/js/158.f2160023.js"><link rel="prefetch" href="/blog/assets/js/159.33ddd8b3.js"><link rel="prefetch" href="/blog/assets/js/16.6a1f4400.js"><link rel="prefetch" href="/blog/assets/js/160.cd0b03b9.js"><link rel="prefetch" href="/blog/assets/js/161.d4b3bb73.js"><link rel="prefetch" href="/blog/assets/js/162.c69e83b1.js"><link rel="prefetch" href="/blog/assets/js/163.9c1b18fa.js"><link rel="prefetch" href="/blog/assets/js/164.854148c8.js"><link rel="prefetch" href="/blog/assets/js/165.aa0c4f4d.js"><link rel="prefetch" href="/blog/assets/js/166.54fc4b36.js"><link rel="prefetch" href="/blog/assets/js/167.ca2d6801.js"><link rel="prefetch" href="/blog/assets/js/168.cf378109.js"><link rel="prefetch" href="/blog/assets/js/169.a298949f.js"><link rel="prefetch" href="/blog/assets/js/17.ad83a175.js"><link rel="prefetch" href="/blog/assets/js/170.1f5f6b47.js"><link rel="prefetch" href="/blog/assets/js/171.aec76c3b.js"><link rel="prefetch" href="/blog/assets/js/172.be4a4852.js"><link rel="prefetch" href="/blog/assets/js/173.80a0f3b5.js"><link rel="prefetch" href="/blog/assets/js/174.e3a39617.js"><link rel="prefetch" href="/blog/assets/js/175.597dc79e.js"><link rel="prefetch" href="/blog/assets/js/176.29eb04a2.js"><link rel="prefetch" href="/blog/assets/js/177.e91f6f26.js"><link rel="prefetch" href="/blog/assets/js/178.34ce2871.js"><link rel="prefetch" href="/blog/assets/js/179.f2cef142.js"><link rel="prefetch" href="/blog/assets/js/18.11cfb1b5.js"><link rel="prefetch" href="/blog/assets/js/180.327428c1.js"><link rel="prefetch" href="/blog/assets/js/181.d6f70081.js"><link rel="prefetch" href="/blog/assets/js/182.e5313823.js"><link rel="prefetch" href="/blog/assets/js/183.d08dbc32.js"><link rel="prefetch" href="/blog/assets/js/184.ccfa8d5d.js"><link rel="prefetch" href="/blog/assets/js/185.9695e392.js"><link rel="prefetch" href="/blog/assets/js/186.3a1b272d.js"><link rel="prefetch" href="/blog/assets/js/187.e11331a6.js"><link rel="prefetch" href="/blog/assets/js/188.2a3eab47.js"><link rel="prefetch" href="/blog/assets/js/189.71a6890e.js"><link rel="prefetch" href="/blog/assets/js/19.1cca0d39.js"><link rel="prefetch" href="/blog/assets/js/190.41f05291.js"><link rel="prefetch" href="/blog/assets/js/191.6db1a29f.js"><link rel="prefetch" href="/blog/assets/js/192.6d6a9425.js"><link rel="prefetch" href="/blog/assets/js/193.1ac4e1e9.js"><link rel="prefetch" href="/blog/assets/js/194.e3056d02.js"><link rel="prefetch" href="/blog/assets/js/195.937d6e29.js"><link rel="prefetch" href="/blog/assets/js/196.775b3da3.js"><link rel="prefetch" href="/blog/assets/js/197.437fe16f.js"><link rel="prefetch" href="/blog/assets/js/198.e02c3fd3.js"><link rel="prefetch" href="/blog/assets/js/199.da036572.js"><link rel="prefetch" href="/blog/assets/js/20.f58b2515.js"><link rel="prefetch" href="/blog/assets/js/200.d70ebfc1.js"><link rel="prefetch" href="/blog/assets/js/201.5a0cc6a8.js"><link rel="prefetch" href="/blog/assets/js/202.b6f4dfe9.js"><link rel="prefetch" href="/blog/assets/js/203.ac5f2eea.js"><link rel="prefetch" href="/blog/assets/js/204.e4197e35.js"><link rel="prefetch" href="/blog/assets/js/205.e988b5e5.js"><link rel="prefetch" href="/blog/assets/js/206.7d6d7ee2.js"><link rel="prefetch" href="/blog/assets/js/207.e9476276.js"><link rel="prefetch" href="/blog/assets/js/208.90d387ec.js"><link rel="prefetch" href="/blog/assets/js/209.01278130.js"><link rel="prefetch" href="/blog/assets/js/21.f2eb7cbe.js"><link rel="prefetch" href="/blog/assets/js/210.08914606.js"><link rel="prefetch" href="/blog/assets/js/211.b5ae3862.js"><link rel="prefetch" href="/blog/assets/js/212.03a9909c.js"><link rel="prefetch" href="/blog/assets/js/213.88999a25.js"><link rel="prefetch" href="/blog/assets/js/214.5e6517ae.js"><link rel="prefetch" href="/blog/assets/js/215.7c05faa3.js"><link rel="prefetch" href="/blog/assets/js/216.0c0d0250.js"><link rel="prefetch" href="/blog/assets/js/217.3e6a1882.js"><link rel="prefetch" href="/blog/assets/js/218.7bdaa47b.js"><link rel="prefetch" href="/blog/assets/js/219.4a9b382a.js"><link rel="prefetch" href="/blog/assets/js/22.0225f4f3.js"><link rel="prefetch" href="/blog/assets/js/220.da13afe0.js"><link rel="prefetch" href="/blog/assets/js/221.b93baddd.js"><link rel="prefetch" href="/blog/assets/js/222.6f88fa87.js"><link rel="prefetch" href="/blog/assets/js/223.23532ff7.js"><link rel="prefetch" href="/blog/assets/js/224.bba40504.js"><link rel="prefetch" href="/blog/assets/js/225.e87911f0.js"><link rel="prefetch" href="/blog/assets/js/226.27fcd8f6.js"><link rel="prefetch" href="/blog/assets/js/227.7075a8c3.js"><link rel="prefetch" href="/blog/assets/js/228.d5363587.js"><link rel="prefetch" href="/blog/assets/js/229.95d21664.js"><link rel="prefetch" href="/blog/assets/js/23.203b3a9e.js"><link rel="prefetch" href="/blog/assets/js/230.eee47d34.js"><link rel="prefetch" href="/blog/assets/js/231.686012e1.js"><link rel="prefetch" href="/blog/assets/js/232.d780f01b.js"><link rel="prefetch" href="/blog/assets/js/233.fba323db.js"><link rel="prefetch" href="/blog/assets/js/234.7ac11688.js"><link rel="prefetch" href="/blog/assets/js/235.61ba2d32.js"><link rel="prefetch" href="/blog/assets/js/24.26ad942d.js"><link rel="prefetch" href="/blog/assets/js/25.e9864d4c.js"><link rel="prefetch" href="/blog/assets/js/26.1a4e2ed9.js"><link rel="prefetch" href="/blog/assets/js/27.f56ff53e.js"><link rel="prefetch" href="/blog/assets/js/28.3c5bd15e.js"><link rel="prefetch" href="/blog/assets/js/29.0104f169.js"><link rel="prefetch" href="/blog/assets/js/3.3ec6f00b.js"><link rel="prefetch" href="/blog/assets/js/30.9aaf650a.js"><link rel="prefetch" href="/blog/assets/js/31.50bfe700.js"><link rel="prefetch" href="/blog/assets/js/32.33630021.js"><link rel="prefetch" href="/blog/assets/js/33.703693c2.js"><link rel="prefetch" href="/blog/assets/js/34.51cfd584.js"><link rel="prefetch" href="/blog/assets/js/35.5614a593.js"><link rel="prefetch" href="/blog/assets/js/36.3f9fb418.js"><link rel="prefetch" href="/blog/assets/js/37.d3471a6e.js"><link rel="prefetch" href="/blog/assets/js/38.303beb9a.js"><link rel="prefetch" href="/blog/assets/js/39.528e5c8c.js"><link rel="prefetch" href="/blog/assets/js/4.f7a68e82.js"><link rel="prefetch" href="/blog/assets/js/40.5d37d2ac.js"><link rel="prefetch" href="/blog/assets/js/41.5e434fb6.js"><link rel="prefetch" href="/blog/assets/js/42.58ebb1e1.js"><link rel="prefetch" href="/blog/assets/js/43.f7344b04.js"><link rel="prefetch" href="/blog/assets/js/44.ba8e2c32.js"><link rel="prefetch" href="/blog/assets/js/45.b59d07a4.js"><link rel="prefetch" href="/blog/assets/js/46.cf56a467.js"><link rel="prefetch" href="/blog/assets/js/47.2307b39c.js"><link rel="prefetch" href="/blog/assets/js/48.0f967628.js"><link rel="prefetch" href="/blog/assets/js/49.e9c76177.js"><link rel="prefetch" href="/blog/assets/js/5.43eb1773.js"><link rel="prefetch" href="/blog/assets/js/50.ef1c92fd.js"><link rel="prefetch" href="/blog/assets/js/51.472db098.js"><link rel="prefetch" href="/blog/assets/js/52.b151aea0.js"><link rel="prefetch" href="/blog/assets/js/53.0df4c526.js"><link rel="prefetch" href="/blog/assets/js/54.352990e8.js"><link rel="prefetch" href="/blog/assets/js/55.27accd61.js"><link rel="prefetch" href="/blog/assets/js/56.91d392d0.js"><link rel="prefetch" href="/blog/assets/js/57.4f8d55c3.js"><link rel="prefetch" href="/blog/assets/js/58.aba5c165.js"><link rel="prefetch" href="/blog/assets/js/59.1f31aefa.js"><link rel="prefetch" href="/blog/assets/js/6.709e31d8.js"><link rel="prefetch" href="/blog/assets/js/60.c4c2ad7c.js"><link rel="prefetch" href="/blog/assets/js/61.84c44795.js"><link rel="prefetch" href="/blog/assets/js/62.847d5a79.js"><link rel="prefetch" href="/blog/assets/js/63.4526d774.js"><link rel="prefetch" href="/blog/assets/js/64.149c457f.js"><link rel="prefetch" href="/blog/assets/js/65.ffb7241e.js"><link rel="prefetch" href="/blog/assets/js/66.ab3a1fd7.js"><link rel="prefetch" href="/blog/assets/js/67.960d17a4.js"><link rel="prefetch" href="/blog/assets/js/68.1ecea3e5.js"><link rel="prefetch" href="/blog/assets/js/69.24a059f9.js"><link rel="prefetch" href="/blog/assets/js/7.3123b0d0.js"><link rel="prefetch" href="/blog/assets/js/70.087b119f.js"><link rel="prefetch" href="/blog/assets/js/71.36ec64ad.js"><link rel="prefetch" href="/blog/assets/js/72.72180002.js"><link rel="prefetch" href="/blog/assets/js/73.76a3edbc.js"><link rel="prefetch" href="/blog/assets/js/74.fb379a54.js"><link rel="prefetch" href="/blog/assets/js/75.eaa559bd.js"><link rel="prefetch" href="/blog/assets/js/76.156bd9c3.js"><link rel="prefetch" href="/blog/assets/js/77.123a161c.js"><link rel="prefetch" href="/blog/assets/js/78.19a324be.js"><link rel="prefetch" href="/blog/assets/js/79.e24877d1.js"><link rel="prefetch" href="/blog/assets/js/8.5c81f7fc.js"><link rel="prefetch" href="/blog/assets/js/80.22910223.js"><link rel="prefetch" href="/blog/assets/js/81.169a78ab.js"><link rel="prefetch" href="/blog/assets/js/82.c300aae5.js"><link rel="prefetch" href="/blog/assets/js/83.fc555e72.js"><link rel="prefetch" href="/blog/assets/js/84.8e8a9c99.js"><link rel="prefetch" href="/blog/assets/js/85.7c060e20.js"><link rel="prefetch" href="/blog/assets/js/86.946a80b1.js"><link rel="prefetch" href="/blog/assets/js/87.8e5e2c47.js"><link rel="prefetch" href="/blog/assets/js/88.d2f97880.js"><link rel="prefetch" href="/blog/assets/js/89.a7a762a6.js"><link rel="prefetch" href="/blog/assets/js/9.dde6002e.js"><link rel="prefetch" href="/blog/assets/js/90.c6447971.js"><link rel="prefetch" href="/blog/assets/js/91.403877ec.js"><link rel="prefetch" href="/blog/assets/js/92.44bb8649.js"><link rel="prefetch" href="/blog/assets/js/93.b9f553db.js"><link rel="prefetch" href="/blog/assets/js/94.27628f49.js"><link rel="prefetch" href="/blog/assets/js/95.7ad3dc73.js"><link rel="prefetch" href="/blog/assets/js/96.adc8f3f6.js"><link rel="prefetch" href="/blog/assets/js/97.f5b76103.js"><link rel="prefetch" href="/blog/assets/js/98.e8878d44.js"><link rel="prefetch" href="/blog/assets/js/99.037be397.js">
    <link rel="stylesheet" href="/blog/assets/css/0.styles.5cae76fb.css">
  </head>
  <body class="theme-mode-light">
    <div id="app" data-server-rendered="true"><div class="theme-container sidebar-open have-rightmenu"><header class="navbar blur"><div title="目录" class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/blog/" class="home-link router-link-active"><img src="/blog/img/logo.png" alt="Evan's blog" class="logo"> <span class="site-name can-hide">Evan's blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/blog/" class="nav-link">首页</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="前端" class="dropdown-title"><a href="/blog/web/" class="link-title">前端</a> <span class="title" style="display:none;">前端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>前端文章</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/blog/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>学习笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/blog/note/javascript/" class="nav-link">《JavaScript教程》</a></li><li class="dropdown-subitem"><a href="/blog/note/js/" class="nav-link">《JavaScript高级程序设计》</a></li><li class="dropdown-subitem"><a href="/blog/note/es6/" class="nav-link">《ES6 教程》</a></li><li class="dropdown-subitem"><a href="/blog/note/vue/" class="nav-link">《Vue》</a></li><li class="dropdown-subitem"><a href="/blog/note/react/" class="nav-link">《React》</a></li><li class="dropdown-subitem"><a href="/blog/note/typescript-axios/" class="nav-link">《TypeScript 从零实现 axios》</a></li><li class="dropdown-subitem"><a href="/blog/note/git/" class="nav-link">《Git》</a></li><li class="dropdown-subitem"><a href="/blog/pages/51afd6/" class="nav-link">TypeScript</a></li><li class="dropdown-subitem"><a href="/blog/pages/4643cd/" class="nav-link">JS设计模式总结</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="页面" class="dropdown-title"><a href="/blog/ui/" class="link-title">页面</a> <span class="title" style="display:none;">页面</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/8309a5b876fc95e3/" class="nav-link">HTML</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/0a83b083bdf257cb/" class="nav-link">CSS</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="技术" class="dropdown-title"><a href="/blog/technology/" class="link-title">技术</a> <span class="title" style="display:none;">技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/9a7ee40fc232253e/" class="nav-link">技术文档</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/4c778760be26d8b3/" class="nav-link">GitHub技巧</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/117708e0af7f0bd9/" class="nav-link">Nodejs</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/41f87d890d0a02af/" class="nav-link">博客搭建</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="更多" class="dropdown-title"><a href="/blog/more/" class="link-title">更多</a> <span class="title" style="display:none;">更多</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/f2a556/" class="nav-link">学习</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/aea6571b7a8bae86/" class="nav-link">面试</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/2d615df9a36a98ed/" class="nav-link">心情杂货</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/baaa02/" class="nav-link">实用技巧</a></li><li class="dropdown-item"><!----> <a href="/blog/friends/" class="nav-link">友情链接</a></li></ul></div></div><div class="nav-item"><a href="/blog/about/" class="nav-link">关于</a></div><div class="nav-item"><a href="/blog/pages/beb6c0bd8a66cea6/" class="nav-link">收藏</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/blog/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/blog/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/blog/archives/" class="nav-link">归档</a></li></ul></div></div> <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <div class="sidebar-hover-trigger"></div> <aside class="sidebar" style="display:none;"><div class="blogger"><img src="https://cdn.jsdelivr.net/gh/xugaoyi/image_store/blog/20200103123203.jpg"> <div class="blogger-info"><h3>Evan Xu</h3> <span>前端界的小学生</span></div></div> <nav class="nav-links"><div class="nav-item"><a href="/blog/" class="nav-link">首页</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="前端" class="dropdown-title"><a href="/blog/web/" class="link-title">前端</a> <span class="title" style="display:none;">前端</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><h4>前端文章</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/blog/pages/8143cc480faf9a11/" class="nav-link">JavaScript</a></li></ul></li><li class="dropdown-item"><h4>学习笔记</h4> <ul class="dropdown-subitem-wrapper"><li class="dropdown-subitem"><a href="/blog/note/javascript/" class="nav-link">《JavaScript教程》</a></li><li class="dropdown-subitem"><a href="/blog/note/js/" class="nav-link">《JavaScript高级程序设计》</a></li><li class="dropdown-subitem"><a href="/blog/note/es6/" class="nav-link">《ES6 教程》</a></li><li class="dropdown-subitem"><a href="/blog/note/vue/" class="nav-link">《Vue》</a></li><li class="dropdown-subitem"><a href="/blog/note/react/" class="nav-link">《React》</a></li><li class="dropdown-subitem"><a href="/blog/note/typescript-axios/" class="nav-link">《TypeScript 从零实现 axios》</a></li><li class="dropdown-subitem"><a href="/blog/note/git/" class="nav-link">《Git》</a></li><li class="dropdown-subitem"><a href="/blog/pages/51afd6/" class="nav-link">TypeScript</a></li><li class="dropdown-subitem"><a href="/blog/pages/4643cd/" class="nav-link">JS设计模式总结</a></li></ul></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="页面" class="dropdown-title"><a href="/blog/ui/" class="link-title">页面</a> <span class="title" style="display:none;">页面</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/8309a5b876fc95e3/" class="nav-link">HTML</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/0a83b083bdf257cb/" class="nav-link">CSS</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="技术" class="dropdown-title"><a href="/blog/technology/" class="link-title">技术</a> <span class="title" style="display:none;">技术</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/9a7ee40fc232253e/" class="nav-link">技术文档</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/4c778760be26d8b3/" class="nav-link">GitHub技巧</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/117708e0af7f0bd9/" class="nav-link">Nodejs</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/41f87d890d0a02af/" class="nav-link">博客搭建</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="更多" class="dropdown-title"><a href="/blog/more/" class="link-title">更多</a> <span class="title" style="display:none;">更多</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/pages/f2a556/" class="nav-link">学习</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/aea6571b7a8bae86/" class="nav-link">面试</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/2d615df9a36a98ed/" class="nav-link">心情杂货</a></li><li class="dropdown-item"><!----> <a href="/blog/pages/baaa02/" class="nav-link">实用技巧</a></li><li class="dropdown-item"><!----> <a href="/blog/friends/" class="nav-link">友情链接</a></li></ul></div></div><div class="nav-item"><a href="/blog/about/" class="nav-link">关于</a></div><div class="nav-item"><a href="/blog/pages/beb6c0bd8a66cea6/" class="nav-link">收藏</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="索引" class="dropdown-title"><a href="/blog/archives/" class="link-title">索引</a> <span class="title" style="display:none;">索引</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/blog/categories/" class="nav-link">分类</a></li><li class="dropdown-item"><!----> <a href="/blog/tags/" class="nav-link">标签</a></li><li class="dropdown-item"><!----> <a href="/blog/archives/" class="nav-link">归档</a></li></ul></div></div> <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><a href="/blog/pages/f344d070a1031ef7/" class="sidebar-link">ECMAScript 6 简介</a></li><li><a href="/blog/pages/c1edd70a6b7c7872/" class="sidebar-link">let 和 const 命令</a></li><li><a href="/blog/pages/b1ab10a62f7564da/" class="sidebar-link">变量的解构赋值</a></li><li><a href="/blog/pages/ca89eca8adeba5f4/" class="sidebar-link">字符串的扩展</a></li><li><a href="/blog/pages/a650b4a0ebfc9350/" class="sidebar-link">字符串的新增方法</a></li><li><a href="/blog/pages/0473261a6ab0ee8c/" class="sidebar-link">正则的扩展</a></li><li><a href="/blog/pages/5dfea9a0f2d1a392/" class="sidebar-link">数值的扩展</a></li><li><a href="/blog/pages/8ed309d668b20264/" class="sidebar-link">函数的扩展</a></li><li><a href="/blog/pages/e34009d60d8bc4b2/" class="sidebar-link">数组的扩展</a></li><li><a href="/blog/pages/b5e3e0a0ff6e9c25/" class="sidebar-link">对象的扩展</a></li><li><a href="/blog/pages/e85e68947502cf90/" class="sidebar-link">对象的新增方法</a></li><li><a href="/blog/pages/02c86eb2792f3262/" class="sidebar-link">Symbol</a></li><li><a href="/blog/pages/0c21dae358fca16b/" class="sidebar-link">Set 和 Map 数据结构</a></li><li><a href="/blog/pages/f56ec2ab97d60483/" class="sidebar-link">Proxy</a></li><li><a href="/blog/pages/74de3e45e4491e95/" class="sidebar-link">Reflect</a></li><li><a href="/blog/pages/2810ae8985e9bd52/" class="sidebar-link">Promise 对象</a></li><li><a href="/blog/pages/48df907ad3570f3d/" class="sidebar-link">Iterator 和 for-of 循环</a></li><li><a href="/blog/pages/718b48ed9ce0adce/" class="sidebar-link">Generator 函数的语法</a></li><li><a href="/blog/pages/75af7031eb66847b/" aria-current="page" class="active sidebar-link">Generator 函数的异步应用</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#传统方法" class="sidebar-link">传统方法</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#基本概念" class="sidebar-link">基本概念</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#异步" class="sidebar-link">异步</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#回调函数" class="sidebar-link">回调函数</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#promise" class="sidebar-link">Promise</a></li></ul></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#generator-函数" class="sidebar-link">Generator 函数</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#协程" class="sidebar-link">协程</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#协程的-generator-函数实现" class="sidebar-link">协程的 Generator 函数实现</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#generator-函数的数据交换和错误处理" class="sidebar-link">Generator 函数的数据交换和错误处理</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#异步任务的封装" class="sidebar-link">异步任务的封装</a></li></ul></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#thunk-函数" class="sidebar-link">Thunk 函数</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#参数的求值策略" class="sidebar-link">参数的求值策略</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#thunk-函数的含义" class="sidebar-link">Thunk 函数的含义</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#javascript-语言的-thunk-函数" class="sidebar-link">JavaScript 语言的 Thunk 函数</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#thunkify-模块" class="sidebar-link">Thunkify 模块</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#generator-函数的流程管理" class="sidebar-link">Generator 函数的流程管理</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#thunk-函数的自动流程管理" class="sidebar-link">Thunk 函数的自动流程管理</a></li></ul></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#co-模块" class="sidebar-link">co 模块</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#基本用法" class="sidebar-link">基本用法</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#co-模块的原理" class="sidebar-link">co 模块的原理</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#基于-promise-对象的自动执行" class="sidebar-link">基于 Promise 对象的自动执行</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#co-模块的源码" class="sidebar-link">co 模块的源码</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#处理并发的异步操作" class="sidebar-link">处理并发的异步操作</a></li><li class="sidebar-sub-header"><a href="/blog/pages/75af7031eb66847b/#实例-处理-stream" class="sidebar-link">实例：处理 Stream</a></li></ul></li></ul></li><li><a href="/blog/pages/3777253e65bac487/" class="sidebar-link">async 函数</a></li><li><a href="/blog/pages/e831e1593c82bbe0/" class="sidebar-link">Class 的基本语法</a></li><li><a href="/blog/pages/83f8c3a0cd87dd83/" class="sidebar-link">Class 的继承</a></li><li><a href="/blog/pages/efe2fb04eb8ac5fb/" class="sidebar-link">Module 的语法</a></li><li><a href="/blog/pages/a79ca2e64ceae213/" class="sidebar-link">Module 的加载实现</a></li><li><a href="/blog/pages/984bf549204bb266/" class="sidebar-link">编程风格</a></li><li><a href="/blog/pages/32c35f7651d6e58e/" class="sidebar-link">读懂 ECMAScript 规格</a></li><li><a href="/blog/pages/16121351be68691b/" class="sidebar-link">异步遍历器</a></li><li><a href="/blog/pages/a2ba314746bfdbdd/" class="sidebar-link">ArrayBuffer</a></li><li><a href="/blog/pages/7188882b8d65af1b/" class="sidebar-link">最新提案</a></li><li><a href="/blog/pages/e97bc1e5626b082c/" class="sidebar-link">装饰器</a></li><li><a href="/blog/pages/1cf50330655efc69/" class="sidebar-link">函数式编程</a></li><li><a href="/blog/pages/6a8e2dc558da1b39/" class="sidebar-link">Mixin</a></li><li><a href="/blog/pages/8e8f80f69b775a56/" class="sidebar-link">SIMD</a></li><li><a href="/blog/pages/ea6f3b870f6dab69/" class="sidebar-link">参考链接</a></li></ul> </aside> <div><main class="page"><div class="theme-vdoing-wrapper "><div class="articleInfo-wrap" data-v-0c557b5e><div class="articleInfo" data-v-0c557b5e><ul class="breadcrumbs" data-v-0c557b5e><li data-v-0c557b5e><a href="/blog/" title="首页" class="iconfont icon-home router-link-active" data-v-0c557b5e></a></li> <li data-v-0c557b5e><a href="/blog/note/es6/#《ES6 教程》笔记" data-v-0c557b5e>《ES6 教程》笔记</a></li></ul> <div class="info" data-v-0c557b5e><div title="作者" class="author iconfont icon-touxiang" data-v-0c557b5e><a href="javascript:;" data-v-0c557b5e>阮一峰</a></div> <div title="创建时间" class="date iconfont icon-riqi" data-v-0c557b5e><a href="javascript:;" data-v-0c557b5e>2020-02-09</a></div> <!----></div></div></div> <!----> <div class="content-wrapper"><div class="right-menu-wrapper"><div class="right-menu-margin"><div class="right-menu-content"></div></div></div> <h1><img src="">Generator 函数的异步应用<!----></h1>  <div class="theme-vdoing-content content__default"><h1 id="generator-函数的异步应用"><a href="#generator-函数的异步应用" class="header-anchor">#</a> Generator 函数的异步应用</h1> <p>异步编程对 JavaScript 语言太重要。JavaScript 语言的执行环境是“单线程”的，如果没有异步编程，根本没法用，非卡死不可。本章主要介绍 Generator 函数如何完成异步操作。
</p> <h2 id="传统方法"><a href="#传统方法" class="header-anchor">#</a> 传统方法</h2> <p>ES6 诞生以前，异步编程的方法，大概有下面四种。</p> <ul><li>回调函数</li> <li>事件监听</li> <li>发布/订阅</li> <li>Promise 对象</li></ul> <p>Generator 函数将 JavaScript 异步编程带入了一个全新的阶段。</p> <h2 id="基本概念"><a href="#基本概念" class="header-anchor">#</a> 基本概念</h2> <h3 id="异步"><a href="#异步" class="header-anchor">#</a> 异步</h3> <p>所谓&quot;异步&quot;，简单说就是一个任务不是连续完成的，可以理解成该任务被人为分成两段，先执行第一段，然后转而执行其他任务，等做好了准备，再回过头执行第二段。</p> <p>比如，有一个任务是读取文件进行处理，任务的第一段是向操作系统发出请求，要求读取文件。然后，程序执行其他任务，等到操作系统返回文件，再接着执行任务的第二段（处理文件）。这种不连续的执行，就叫做异步。</p> <p>相应地，连续的执行就叫做同步。由于是连续执行，不能插入其他任务，所以操作系统从硬盘读取文件的这段时间，程序只能干等着。</p> <h3 id="回调函数"><a href="#回调函数" class="header-anchor">#</a> 回调函数</h3> <p>JavaScript 语言对异步编程的实现，就是回调函数。所谓回调函数，就是把任务的第二段单独写在一个函数里面，等到重新执行这个任务的时候，就直接调用这个函数。回调函数的英语名字<code>callback</code>，直译过来就是&quot;重新调用&quot;。</p> <p>读取文件进行处理，是这样写的。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'/etc/passwd'</span><span class="token punctuation">,</span> <span class="token string">'utf-8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">throw</span> err<span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>上面代码中，<code>readFile</code>函数的第三个参数，就是回调函数，也就是任务的第二段。等到操作系统返回了<code>/etc/passwd</code>这个文件以后，回调函数才会执行。</p> <p>一个有趣的问题是，为什么 Node 约定，回调函数的第一个参数，必须是错误对象<code>err</code>（如果没有错误，该参数就是<code>null</code>）？</p> <p>原因是执行分成两段，第一段执行完以后，任务所在的上下文环境就已经结束了。在这以后抛出的错误，原来的上下文环境已经无法捕捉，只能当作参数，传入第二段。</p> <h3 id="promise"><a href="#promise" class="header-anchor">#</a> Promise</h3> <p>回调函数本身并没有问题，它的问题出现在多个回调函数嵌套。假定读取<code>A</code>文件之后，再读取<code>B</code>文件，代码如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>fileA<span class="token punctuation">,</span> <span class="token string">'utf-8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>fileB<span class="token punctuation">,</span> <span class="token string">'utf-8'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ...</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>不难想象，如果依次读取两个以上的文件，就会出现多重嵌套。代码不是纵向发展，而是横向发展，很快就会乱成一团，无法管理。因为多个异步操作形成了强耦合，只要有一个操作需要修改，它的上层回调函数和下层回调函数，可能都要跟着修改。这种情况就称为&quot;回调函数地狱&quot;（callback hell）。</p> <p>Promise 对象就是为了解决这个问题而提出的。它不是新的语法功能，而是一种新的写法，允许将回调函数的嵌套，改成链式调用。采用 Promise，连续读取多个文件，写法如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> readFile <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs-readfile-promise'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token function">readFile</span><span class="token punctuation">(</span>fileA<span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>data<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token function">readFile</span><span class="token punctuation">(</span>fileB<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>data<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>上面代码中，我使用了<code>fs-readfile-promise</code>模块，它的作用就是返回一个 Promise 版本的<code>readFile</code>函数。Promise 提供<code>then</code>方法加载回调函数，<code>catch</code>方法捕捉执行过程中抛出的错误。</p> <p>可以看到，Promise 的写法只是回调函数的改进，使用<code>then</code>方法以后，异步任务的两段执行看得更清楚了，除此以外，并无新意。</p> <p>Promise 的最大问题是代码冗余，原来的任务被 Promise 包装了一下，不管什么操作，一眼看去都是一堆<code>then</code>，原来的语义变得很不清楚。</p> <p>那么，有没有更好的写法呢？</p> <h2 id="generator-函数"><a href="#generator-函数" class="header-anchor">#</a> Generator 函数</h2> <h3 id="协程"><a href="#协程" class="header-anchor">#</a> 协程</h3> <p>传统的编程语言，早有异步编程的解决方案（其实是多任务的解决方案）。其中有一种叫做&quot;协程&quot;（coroutine），意思是<strong>多个线程互相协作，完成异步任务</strong>。</p> <p>协程有点像函数，又有点像线程。它的运行流程大致如下。</p> <ul><li>第一步，协程<code>A</code>开始执行。</li> <li>第二步，协程<code>A</code>执行到一半，进入暂停，执行权转移到协程<code>B</code>。</li> <li>第三步，（一段时间后）协程<code>B</code>交还执行权。</li> <li>第四步，协程<code>A</code>恢复执行。</li></ul> <p>上面流程的协程<code>A</code>，就是异步任务，因为它分成两段（或多段）执行。</p> <p>举例来说，读取文件的协程写法如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">asyncJob</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// ...其他代码</span>
  <span class="token keyword">var</span> f <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFile</span><span class="token punctuation">(</span>fileA<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// ...其他代码</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面代码的函数<code>asyncJob</code>是一个协程，它的奥妙就在其中的<code>yield</code>命令。它表示执行到此处，执行权将交给其他协程。也就是说，<code>yield</code>命令是异步两个阶段的分界线。</p> <p>协程遇到<code>yield</code>命令就暂停，等到执行权返回，再从暂停的地方继续往后执行。它的最大优点，就是代码的写法非常像同步操作，如果去除<code>yield</code>命令，简直一模一样。</p> <h3 id="协程的-generator-函数实现"><a href="#协程的-generator-函数实现" class="header-anchor">#</a> 协程的 Generator 函数实现</h3> <p>Generator 函数是协程在 ES6 的实现，最大特点就是可以交出函数的执行权（即暂停执行）。</p> <p>整个 Generator 函数就是一个封装的异步任务，或者说是异步任务的容器。异步操作需要暂停的地方，都用<code>yield</code>语句注明。Generator 函数的执行方法如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token parameter">x</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> y <span class="token operator">=</span> <span class="token keyword">yield</span> x <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> y<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// { value: 3, done: false }</span>
g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// { value: undefined, done: true }</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，调用 Generator 函数，会返回一个内部指针（即遍历器）<code>g</code>。这是 Generator 函数不同于普通函数的另一个地方，即执行它不会返回结果，<strong>返回的是指针对象。调用指针<code>g</code>的<code>next</code>方法，会移动内部指针</strong>（即执行异步任务的第一段），指向第一个遇到的<code>yield</code>语句，上例是执行到<code>x + 2</code>为止。</p> <p>换言之，<strong><code>next</code>方法的作用是分阶段执行<code>Generator</code>函数</strong>。每次调用<code>next</code>方法，会返回一个对象，表示当前阶段的信息（<code>value</code>属性和<code>done</code>属性）。<strong><code>value</code>属性是<code>yield</code>语句后面表达式的值，表示当前阶段的值</strong>；<code>done</code>属性是一个布尔值，表示 Generator 函数是否执行完毕，即是否还有下一个阶段。</p> <h3 id="generator-函数的数据交换和错误处理"><a href="#generator-函数的数据交换和错误处理" class="header-anchor">#</a> Generator 函数的数据交换和错误处理</h3> <p><strong>Generator 函数可以暂停执行和恢复执行</strong>，这是它能封装异步任务的根本原因。除此之外，它还有两个特性，使它可以作为异步编程的完整解决方案：<strong>函数体内外的数据交换和错误处理机制</strong>。</p> <p><strong><code>next</code>返回值的 value 属性，是 Generator 函数向外输出数据；<code>next</code>方法还可以接受参数，向 Generator 函数体内输入数据。</strong></p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token parameter">x</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> y <span class="token operator">=</span> <span class="token keyword">yield</span> x <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> y<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// { value: 3, done: false }</span>
g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment">// { value: 2, done: true }</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，第一个<code>next</code>方法的<code>value</code>属性，返回表达式<code>x + 2</code>的值<code>3</code>。第二个<code>next</code>方法带有参数<code>2</code>，这个参数可以传入 Generator 函数，作为上个阶段异步任务的返回结果，被函数体内的变量<code>y</code>接收。因此，这一步的<code>value</code>属性，返回的就是<code>2</code>（变量<code>y</code>的值）。</p> <p><strong>Generator 函数内部还可以部署错误处理代码，捕获函数体外抛出的错误</strong>。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token parameter">x</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">try</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> y <span class="token operator">=</span> <span class="token keyword">yield</span> x <span class="token operator">+</span> <span class="token number">2</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token keyword">return</span> y<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
g<span class="token punctuation">.</span><span class="token function">throw</span><span class="token punctuation">(</span><span class="token string">'出错了'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 出错了</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>上面代码的最后一行，Generator 函数体外，使用指针对象的<code>throw</code>方法抛出的错误，可以被函数体内的<code>try...catch</code>代码块捕获。这意味着，<strong>出错的代码与处理错误的代码，实现了时间和空间上的分离</strong>，这对于异步编程无疑是很重要的。</p> <h3 id="异步任务的封装"><a href="#异步任务的封装" class="header-anchor">#</a> 异步任务的封装</h3> <p>下面看看如何使用 Generator 函数，执行一个真实的异步任务。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> fetch <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'node-fetch'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> url <span class="token operator">=</span> <span class="token string">'https://api.github.com/users/github'</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> result <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">fetch</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>bio<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面代码中，Generator 函数封装了一个异步操作，该操作先读取一个远程接口，然后从 JSON 格式的数据解析信息。就像前面说过的，这段代码非常像同步操作，除了加上了<code>yield</code>命令。</p> <p>执行这段代码的方法如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> result <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

result<span class="token punctuation">.</span>value<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">return</span> data<span class="token punctuation">.</span><span class="token function">json</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，首先执行 Generator 函数，获取遍历器对象，然后使用<code>next</code>方法（第二行），执行异步任务的第一阶段。由于<code>Fetch</code>模块返回的是一个 Promise 对象，因此要用<code>then</code>方法调用下一个<code>next</code>方法。</p> <p>可以看到，<strong>虽然 Generator 函数将异步操作表示得很简洁，但是流程管理却不方便</strong>（即何时执行第一阶段、何时执行第二阶段）。</p> <h2 id="thunk-函数"><a href="#thunk-函数" class="header-anchor">#</a> Thunk 函数</h2> <p>Thunk 函数是自动执行 Generator 函数的一种方法。</p> <h3 id="参数的求值策略"><a href="#参数的求值策略" class="header-anchor">#</a> 参数的求值策略</h3> <p>Thunk 函数早在上个世纪 60 年代就诞生了。</p> <p>那时，编程语言刚刚起步，计算机学家还在研究，编译器怎么写比较好。一个争论的焦点是&quot;求值策略&quot;，即函数的参数到底应该何时求值。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> x <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>

<span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">m</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> m <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token function">f</span><span class="token punctuation">(</span>x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>上面代码先定义函数<code>f</code>，然后向它传入表达式<code>x + 5</code>。请问，这个表达式应该何时求值？</p> <p>一种意见是&quot;传值调用&quot;（call by value），即在进入函数体之前，就计算<code>x + 5</code>的值（等于 6），再将这个值传入函数<code>f</code>。C 语言就采用这种策略。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">f</span><span class="token punctuation">(</span>x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">)</span>
<span class="token comment">// 传值调用时，等同于</span>
<span class="token function">f</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>另一种意见是“传名调用”（call by name），即直接将表达式<code>x + 5</code>传入函数体，只在用到它的时候求值。Haskell 语言采用这种策略。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">f</span><span class="token punctuation">(</span>x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">)</span>
<span class="token comment">// 传名调用时，等同于</span>
<span class="token punctuation">(</span>x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">2</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>传值调用和传名调用，哪一种比较好？</p> <p>回答是各有利弊。传值调用比较简单，但是对参数求值的时候，实际上还没用到这个参数，有可能造成性能损失。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">a<span class="token punctuation">,</span> b</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">return</span> b<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token function">f</span><span class="token punctuation">(</span><span class="token number">3</span> <span class="token operator">*</span> x <span class="token operator">*</span> x <span class="token operator">-</span> <span class="token number">2</span> <span class="token operator">*</span> x <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>上面代码中，函数<code>f</code>的第一个参数是一个复杂的表达式，但是函数体内根本没用到。对这个参数求值，实际上是不必要的。因此，有一些计算机学家倾向于&quot;传名调用&quot;，即只在执行时求值。</p> <h3 id="thunk-函数的含义"><a href="#thunk-函数的含义" class="header-anchor">#</a> Thunk 函数的含义</h3> <p>编译器的“传名调用”实现，往往是将参数放到一个临时函数之中，再将这个临时函数传入函数体。这个临时函数就叫做 Thunk 函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">m</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> m <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token function">f</span><span class="token punctuation">(</span>x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 等同于</span>

<span class="token keyword">var</span> <span class="token function-variable function">thunk</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> x <span class="token operator">+</span> <span class="token number">5</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">thunk</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token function">thunk</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>上面代码中，函数 f 的参数<code>x + 5</code>被一个函数替换了。凡是用到原参数的地方，对<code>Thunk</code>函数求值即可。</p> <p>这就是 Thunk 函数的定义，<strong>它是“传名调用”的一种实现策略，用来替换某个表达式。</strong></p> <h3 id="javascript-语言的-thunk-函数"><a href="#javascript-语言的-thunk-函数" class="header-anchor">#</a> JavaScript 语言的 Thunk 函数</h3> <p>JavaScript 语言是传值调用，它的 Thunk 函数含义有所不同。在 JavaScript 语言中，Thunk 函数替换的不是表达式，而是多参数函数，将其替换成一个只接受回调函数作为参数的单参数函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 正常版本的readFile（多参数版本）</span>
fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>fileName<span class="token punctuation">,</span> callback<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// Thunk版本的readFile（单参数版本）</span>
<span class="token keyword">var</span> <span class="token function-variable function">Thunk</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">fileName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">callback</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>fileName<span class="token punctuation">,</span> callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> readFileThunk <span class="token operator">=</span> <span class="token function">Thunk</span><span class="token punctuation">(</span>fileName<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">readFileThunk</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>上面代码中，<code>fs</code>模块的<code>readFile</code>方法是一个多参数函数，两个参数分别为文件名和回调函数。经过转换器处理，它变成了一个单参数函数，只接受回调函数作为参数。这个单参数版本，就叫做 Thunk 函数。</p> <p><strong>任何函数，只要参数有回调函数，就能写成 Thunk 函数的形式</strong>。下面是一个简单的 Thunk 函数转换器。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// ES5版本</span>
<span class="token keyword">var</span> <span class="token function-variable function">Thunk</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">fn</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">var</span> args <span class="token operator">=</span> <span class="token class-name">Array</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>arguments<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">callback</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      args<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token comment">// ES6版本</span>
<span class="token keyword">const</span> <span class="token function-variable function">Thunk</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">fn</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter"><span class="token operator">...</span>args</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">callback</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">,</span> callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br></div></div><p>使用上面的转换器，生成<code>fs.readFile</code>的 Thunk 函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> readFileThunk <span class="token operator">=</span> <span class="token function">Thunk</span><span class="token punctuation">(</span>fs<span class="token punctuation">.</span>readFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">readFileThunk</span><span class="token punctuation">(</span>fileA<span class="token punctuation">)</span><span class="token punctuation">(</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>下面是另一个完整的例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">a<span class="token punctuation">,</span> cb</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token function">cb</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">const</span> ft <span class="token operator">=</span> <span class="token function">Thunk</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token function">ft</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">(</span>console<span class="token punctuation">.</span>log<span class="token punctuation">)</span> <span class="token comment">// 1</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><h3 id="thunkify-模块"><a href="#thunkify-模块" class="header-anchor">#</a> Thunkify 模块</h3> <p>生产环境的转换器，建议使用 Thunkify 模块。</p> <p>首先是安装。</p> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>$ <span class="token function">npm</span> <span class="token function">install</span> thunkify
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>使用方式如下。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> thunkify <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'thunkify'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> read <span class="token operator">=</span> <span class="token function">thunkify</span><span class="token punctuation">(</span>fs<span class="token punctuation">.</span>readFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">read</span><span class="token punctuation">(</span><span class="token string">'package.json'</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> str</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// ...</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>Thunkify 的源码与上一节那个简单的转换器非常像。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">thunkify</span><span class="token punctuation">(</span><span class="token parameter">fn</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> args <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Array</span><span class="token punctuation">(</span>arguments<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> ctx <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> args<span class="token punctuation">.</span>length<span class="token punctuation">;</span> <span class="token operator">++</span>i<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      args<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> arguments<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">return</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">done</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">var</span> called<span class="token punctuation">;</span>

      args<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>called<span class="token punctuation">)</span> <span class="token keyword">return</span><span class="token punctuation">;</span>
        called <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token function">done</span><span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> arguments<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">done</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br></div></div><p>它的源码主要多了一个检查机制，变量<code>called</code>确保回调函数只运行一次。这样的设计与下文的 Generator 函数相关。请看下面的例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">f</span><span class="token punctuation">(</span><span class="token parameter">a<span class="token punctuation">,</span> b<span class="token punctuation">,</span> callback</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> sum <span class="token operator">=</span> a <span class="token operator">+</span> b<span class="token punctuation">;</span>
  <span class="token function">callback</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token function">callback</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> ft <span class="token operator">=</span> <span class="token function">thunkify</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> print <span class="token operator">=</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>console<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">ft</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">(</span>print<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 3</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上面代码中，由于<code>thunkify</code>只允许回调函数执行一次，所以只输出一行结果。</p> <h3 id="generator-函数的流程管理"><a href="#generator-函数的流程管理" class="header-anchor">#</a> Generator 函数的流程管理</h3> <p>你可能会问， Thunk 函数有什么用？回答是以前确实没什么用，但是 ES6 有了 Generator 函数，<strong>Thunk 函数现在可以用于 Generator 函数的自动流程管理</strong>。</p> <p>Generator 函数可以自动执行。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// ...</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> res <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">while</span><span class="token punctuation">(</span><span class="token operator">!</span>res<span class="token punctuation">.</span>done<span class="token punctuation">)</span><span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>res<span class="token punctuation">.</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
  res <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上面代码中，Generator 函数<code>gen</code>会自动执行完所有步骤。</p> <p>但是，这不适合异步操作。如果必须保证前一步执行完，才能执行后一步，上面的自动执行就不可行。这时，Thunk 函数就能派上用处。以读取文件为例。下面的 Generator 函数封装了两个异步操作。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> thunkify <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'thunkify'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> readFileThunk <span class="token operator">=</span> <span class="token function">thunkify</span><span class="token punctuation">(</span>fs<span class="token punctuation">.</span>readFile<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> <span class="token function-variable function">gen</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> r1 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFileThunk</span><span class="token punctuation">(</span><span class="token string">'/etc/fstab'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>r1<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> r2 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFileThunk</span><span class="token punctuation">(</span><span class="token string">'/etc/shells'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>r2<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上面代码中，<code>yield</code>命令用于将程序的执行权移出 Generator 函数，那么就需要一种方法，将执行权再交还给 Generator 函数。</p> <p>这种方法就是 Thunk 函数，因为它可以在回调函数里，将执行权交还给 Generator 函数。为了便于理解，我们先看如何手动执行上面这个 Generator 函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> r1 <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
r1<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">throw</span> err<span class="token punctuation">;</span>
  <span class="token keyword">var</span> r2 <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  r2<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">throw</span> err<span class="token punctuation">;</span>
    g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>上面代码中，变量<code>g</code>是 Generator 函数的内部指针，表示目前执行到哪一步。<code>next</code>方法负责将指针移动到下一步，并返回该步的信息（<code>value</code>属性和<code>done</code>属性）。</p> <p>仔细查看上面的代码，可以发现 Generator 函数的执行过程，其实是将同一个回调函数，反复传入<code>next</code>方法的<code>value</code>属性。这使得我们可以用递归来自动完成这个过程。</p> <h3 id="thunk-函数的自动流程管理"><a href="#thunk-函数的自动流程管理" class="header-anchor">#</a> Thunk 函数的自动流程管理</h3> <p>Thunk 函数真正的威力，在于可以自动执行 Generator 函数。下面就是一个基于 Thunk 函数的 Generator 执行器。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token parameter">fn</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> gen <span class="token operator">=</span> <span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">function</span> <span class="token function">next</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> result <span class="token operator">=</span> gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>result<span class="token punctuation">.</span>done<span class="token punctuation">)</span> <span class="token keyword">return</span><span class="token punctuation">;</span>
    result<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span>next<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">g</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// ...</span>
<span class="token punctuation">}</span>

<span class="token function">run</span><span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>上面代码的<code>run</code>函数，就是一个 Generator 函数的自动执行器。内部的<code>next</code>函数就是 Thunk 的回调函数。<code>next</code>函数先将指针移到 Generator 函数的下一步（<code>gen.next</code>方法），然后判断 Generator 函数是否结束（<code>result.done</code>属性），如果没结束，就将<code>next</code>函数再传入 Thunk 函数（<code>result.value</code>属性），否则就直接退出。</p> <p>有了这个执行器，执行 Generator 函数方便多了。不管内部有多少个异步操作，直接把 Generator 函数传入<code>run</code>函数即可。当然，前提是每一个异步操作，都要是 Thunk 函数，也就是说，跟在<code>yield</code>命令后面的必须是 Thunk 函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> <span class="token function-variable function">g</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> f1 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFileThunk</span><span class="token punctuation">(</span><span class="token string">'fileA'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> f2 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFileThunk</span><span class="token punctuation">(</span><span class="token string">'fileB'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// ...</span>
  <span class="token keyword">var</span> fn <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFileThunk</span><span class="token punctuation">(</span><span class="token string">'fileN'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token function">run</span><span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>上面代码中，函数<code>g</code>封装了<code>n</code>个异步的读取文件操作，只要执行<code>run</code>函数，这些操作就会自动完成。这样一来，异步操作不仅可以写得像同步操作，而且一行代码就可以执行。</p> <p>Thunk 函数并不是 Generator 函数自动执行的唯一方案。因为自动执行的关键是，必须有一种机制，自动控制 Generator 函数的流程，接收和交还程序的执行权。回调函数可以做到这一点，Promise 对象也可以做到这一点。</p> <h2 id="co-模块"><a href="#co-模块" class="header-anchor">#</a> co 模块</h2> <h3 id="基本用法"><a href="#基本用法" class="header-anchor">#</a> 基本用法</h3> <p><a href="https://github.com/tj/co" target="_blank" rel="noopener noreferrer">co 模块<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>是著名程序员 TJ Holowaychuk 于 2013 年 6 月发布的一个小工具，用于 Generator 函数的自动执行。</p> <p>下面是一个 Generator 函数，用于依次读取两个文件。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> <span class="token function-variable function">gen</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> f1 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'/etc/fstab'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> f2 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'/etc/shells'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>f1<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>f2<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>co 模块可以让你不用编写 Generator 函数的执行器。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> co <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'co'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">co</span><span class="token punctuation">(</span>gen<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>上面代码中，Generator 函数只要传入<code>co</code>函数，就会自动执行。</p> <p><code>co</code>函数返回一个<code>Promise</code>对象，因此可以用<code>then</code>方法添加回调函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">co</span><span class="token punctuation">(</span>gen<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'Generator 函数执行完成'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>上面代码中，等到 Generator 函数执行结束，就会输出一行提示。</p> <h3 id="co-模块的原理"><a href="#co-模块的原理" class="header-anchor">#</a> co 模块的原理</h3> <p>为什么 co 可以自动执行 Generator 函数？</p> <p>前面说过，Generator 就是一个异步操作的容器。它的自动执行需要一种机制，当异步操作有了结果，能够自动交回执行权。</p> <p>两种方法可以做到这一点。</p> <p>（1）回调函数。将异步操作包装成 Thunk 函数，在回调函数里面交回执行权。</p> <p>（2）Promise 对象。将异步操作包装成 Promise 对象，用<code>then</code>方法交回执行权。</p> <p>co 模块其实就是将两种自动执行器（Thunk 函数和 Promise 对象），包装成一个模块。使用 co 的前提条件是，Generator 函数的<code>yield</code>命令后面，只能是 Thunk 函数或 Promise 对象。如果数组或对象的成员，全部都是 Promise 对象，也可以使用 co，详见后文的例子。</p> <p>上一节已经介绍了基于 Thunk 函数的自动执行器。下面来看，基于 Promise 对象的自动执行器。这是理解 co 模块必须的。</p> <h3 id="基于-promise-对象的自动执行"><a href="#基于-promise-对象的自动执行" class="header-anchor">#</a> 基于 Promise 对象的自动执行</h3> <p>还是沿用上面的例子。首先，把<code>fs</code>模块的<code>readFile</code>方法包装成一个 Promise 对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> <span class="token function-variable function">readFile</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">fileName</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    fs<span class="token punctuation">.</span><span class="token function">readFile</span><span class="token punctuation">(</span>fileName<span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">error<span class="token punctuation">,</span> data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>error<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">reject</span><span class="token punctuation">(</span>error<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token function">resolve</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> <span class="token function-variable function">gen</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> f1 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'/etc/fstab'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> f2 <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token function">readFile</span><span class="token punctuation">(</span><span class="token string">'/etc/shells'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>f1<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>f2<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>然后，手动执行上面的 Generator 函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">.</span>value<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>手动执行其实就是用<code>then</code>方法，层层添加回调函数。理解了这一点，就可以写出一个自动执行器。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token parameter">gen</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">var</span> g <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">function</span> <span class="token function">next</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">var</span> result <span class="token operator">=</span> g<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>result<span class="token punctuation">.</span>done<span class="token punctuation">)</span> <span class="token keyword">return</span> result<span class="token punctuation">.</span>value<span class="token punctuation">;</span>
    result<span class="token punctuation">.</span>value<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">data</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token function">next</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token function">run</span><span class="token punctuation">(</span>gen<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p>上面代码中，只要 Generator 函数还没执行到最后一步，<code>next</code>函数就调用自身，以此实现自动执行。</p> <h3 id="co-模块的源码"><a href="#co-模块的源码" class="header-anchor">#</a> co 模块的源码</h3> <p>co 就是上面那个自动执行器的扩展，它的源码只有几十行，非常简单。</p> <p>首先，co 函数接受 Generator 函数作为参数，返回一个 Promise 对象。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">co</span><span class="token punctuation">(</span><span class="token parameter">gen</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> ctx <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>在返回的 Promise 对象里面，co 先检查参数<code>gen</code>是否为 Generator 函数。如果是，就执行该函数，得到一个内部指针对象；如果不是就返回，并将 Promise 对象的状态改为<code>resolved</code>。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">co</span><span class="token punctuation">(</span><span class="token parameter">gen</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> ctx <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> gen <span class="token operator">===</span> <span class="token string">'function'</span><span class="token punctuation">)</span> gen <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>ctx<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>gen <span class="token operator">||</span> <span class="token keyword">typeof</span> gen<span class="token punctuation">.</span>next <span class="token operator">!==</span> <span class="token string">'function'</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">resolve</span><span class="token punctuation">(</span>gen<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>接着，co 将 Generator 函数的内部指针对象的<code>next</code>方法，包装成<code>onFulfilled</code>函数。这主要是为了能够捕捉抛出的错误。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">co</span><span class="token punctuation">(</span><span class="token parameter">gen</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> ctx <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> gen <span class="token operator">===</span> <span class="token string">'function'</span><span class="token punctuation">)</span> gen <span class="token operator">=</span> <span class="token function">gen</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>ctx<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>gen <span class="token operator">||</span> <span class="token keyword">typeof</span> gen<span class="token punctuation">.</span>next <span class="token operator">!==</span> <span class="token string">'function'</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">resolve</span><span class="token punctuation">(</span>gen<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token function">onFulfilled</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">function</span> <span class="token function">onFulfilled</span><span class="token punctuation">(</span><span class="token parameter">res</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">var</span> ret<span class="token punctuation">;</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        ret <span class="token operator">=</span> gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token function">reject</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token function">next</span><span class="token punctuation">(</span>ret<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br></div></div><p>最后，就是关键的<code>next</code>函数，它会反复调用自身。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">next</span><span class="token punctuation">(</span><span class="token parameter">ret</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>ret<span class="token punctuation">.</span>done<span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token function">resolve</span><span class="token punctuation">(</span>ret<span class="token punctuation">.</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> value <span class="token operator">=</span> <span class="token function">toPromise</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> ret<span class="token punctuation">.</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">&amp;&amp;</span> <span class="token function">isPromise</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token keyword">return</span> value<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span>onFulfilled<span class="token punctuation">,</span> onRejected<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token function">onRejected</span><span class="token punctuation">(</span>
    <span class="token keyword">new</span> <span class="token class-name">TypeError</span><span class="token punctuation">(</span>
      <span class="token string">'You may only yield a function, promise, generator, array, or object, '</span>
      <span class="token operator">+</span> <span class="token string">'but the following object was passed: &quot;'</span>
      <span class="token operator">+</span> <span class="token function">String</span><span class="token punctuation">(</span>ret<span class="token punctuation">.</span>value<span class="token punctuation">)</span>
      <span class="token operator">+</span> <span class="token string">'&quot;'</span>
    <span class="token punctuation">)</span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>上面代码中，<code>next</code>函数的内部代码，一共只有四行命令。</p> <p>第一行，检查当前是否为 Generator 函数的最后一步，如果是就返回。</p> <p>第二行，确保每一步的返回值，是 Promise 对象。</p> <p>第三行，使用<code>then</code>方法，为返回值加上回调函数，然后通过<code>onFulfilled</code>函数再次调用<code>next</code>函数。</p> <p>第四行，在参数不符合要求的情况下（参数非 Thunk 函数和 Promise 对象），将 Promise 对象的状态改为<code>rejected</code>，从而终止执行。</p> <h3 id="处理并发的异步操作"><a href="#处理并发的异步操作" class="header-anchor">#</a> 处理并发的异步操作</h3> <p>co 支持并发的异步操作，即允许某些操作同时进行，等到它们全部完成，才进行下一步。</p> <p>这时，要把并发的操作都放在数组或对象里面，跟在<code>yield</code>语句后面。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 数组的写法</span>
<span class="token function">co</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> res <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token punctuation">[</span>
    Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
  <span class="token punctuation">]</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span>onerror<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 对象的写法</span>
<span class="token function">co</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> res <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token punctuation">{</span>
    <span class="token number">1</span><span class="token operator">:</span> Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token number">2</span><span class="token operator">:</span> Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span>onerror<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p>下面是另一个例子。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token function">co</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token operator">*</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> values <span class="token operator">=</span> <span class="token punctuation">[</span>n1<span class="token punctuation">,</span> n2<span class="token punctuation">,</span> n3<span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">yield</span> values<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>somethingAsync<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">function</span><span class="token operator">*</span> <span class="token function">somethingAsync</span><span class="token punctuation">(</span><span class="token parameter">x</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// do something async</span>
  <span class="token keyword">return</span> y
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>上面的代码允许并发三个<code>somethingAsync</code>异步操作，等到它们全部完成，才会进行下一步。</p> <h3 id="实例-处理-stream"><a href="#实例-处理-stream" class="header-anchor">#</a> 实例：处理 Stream</h3> <p>Node 提供 Stream 模式读写数据，特点是一次只处理数据的一部分，数据分成一块块依次处理，就好像“数据流”一样。这对于处理大规模数据非常有利。Stream 模式使用 EventEmitter API，会释放三个事件。</p> <ul><li><code>data</code>事件：下一块数据块已经准备好了。</li> <li><code>end</code>事件：整个“数据流”处理完了。</li> <li><code>error</code>事件：发生错误。</li></ul> <p>使用<code>Promise.race()</code>函数，可以判断这三个事件之中哪一个最先发生，只有当<code>data</code>事件最先发生时，才进入下一个数据块的处理。从而，我们可以通过一个<code>while</code>循环，完成所有数据的读取。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> co <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'co'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> fs <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'fs'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">const</span> stream <span class="token operator">=</span> fs<span class="token punctuation">.</span><span class="token function">createReadStream</span><span class="token punctuation">(</span><span class="token string">'./les_miserables.txt'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> valjeanCount <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

<span class="token function">co</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token operator">*</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">while</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> res <span class="token operator">=</span> <span class="token keyword">yield</span> Promise<span class="token punctuation">.</span><span class="token function">race</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
      <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token parameter">resolve</span> <span class="token operator">=&gt;</span> stream<span class="token punctuation">.</span><span class="token function">once</span><span class="token punctuation">(</span><span class="token string">'data'</span><span class="token punctuation">,</span> resolve<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
      <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token parameter">resolve</span> <span class="token operator">=&gt;</span> stream<span class="token punctuation">.</span><span class="token function">once</span><span class="token punctuation">(</span><span class="token string">'end'</span><span class="token punctuation">,</span> resolve<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
      <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> stream<span class="token punctuation">.</span><span class="token function">once</span><span class="token punctuation">(</span><span class="token string">'error'</span><span class="token punctuation">,</span> reject<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>res<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">break</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    stream<span class="token punctuation">.</span><span class="token function">removeAllListeners</span><span class="token punctuation">(</span><span class="token string">'data'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    stream<span class="token punctuation">.</span><span class="token function">removeAllListeners</span><span class="token punctuation">(</span><span class="token string">'end'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    stream<span class="token punctuation">.</span><span class="token function">removeAllListeners</span><span class="token punctuation">(</span><span class="token string">'error'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    valjeanCount <span class="token operator">+=</span> <span class="token punctuation">(</span>res<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">match</span><span class="token punctuation">(</span><span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">valjean</span><span class="token regex-delimiter">/</span><span class="token regex-flags">ig</span></span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">.</span>length<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'count:'</span><span class="token punctuation">,</span> valjeanCount<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// count: 1120</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br></div></div><p>上面代码采用 Stream 模式读取《悲惨世界》的文本文件，对于每个数据块都使用<code>stream.once</code>方法，在<code>data</code>、<code>end</code>、<code>error</code>三个事件上添加一次性回调函数。变量<code>res</code>只有在<code>data</code>事件发生时才有值，然后累加每个数据块之中<code>valjean</code>这个词出现的次数。</p></div></div>  <div class="page-edit"><div class="edit-link"><a href="https://github.com/xugaoyi/vuepress-theme-vdoing/edit/master/docs/《ES6 教程》笔记/19.Generator 函数的异步应用.md" target="_blank" rel="noopener noreferrer">编辑</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <div class="tags"><a href="/blog/tags/?tag=ES6" title="标签">#ES6</a></div> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">2022/01/18, 12:59:48</span></div></div> <div class="page-nav-wapper"><div class="page-nav-centre-wrap"><a href="/blog/pages/718b48ed9ce0adce/" class="page-nav-centre page-nav-centre-prev"><div class="tooltip">Generator 函数的语法</div></a> <a href="/blog/pages/3777253e65bac487/" class="page-nav-centre page-nav-centre-next"><div class="tooltip">async 函数</div></a></div> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/blog/pages/718b48ed9ce0adce/" class="prev">Generator 函数的语法</a></span> <span class="next"><a href="/blog/pages/3777253e65bac487/">async 函数</a>→
      </span></p></div></div></div> <div class="article-list"><div class="article-title"><a href="/blog/archives/" class="iconfont icon-bi">最近更新</a></div> <div class="article-wrapper"><dl><dd>01</dd> <dt><a href="/blog/pages/dcebaf/"><div>
            一行代码“黑”掉任意网站
            <span class="title-tag">
              原创
            </span></div></a> <span class="date">11-25</span></dt></dl><dl><dd>02</dd> <dt><a href="/blog/pages/a61298/"><div>
            33个非常实用的JavaScript一行代码
            <!----></div></a> <span class="date">11-02</span></dt></dl><dl><dd>03</dd> <dt><a href="/blog/pages/82baa3/"><div>
            使用State Hook
            <!----></div></a> <span class="date">04-06</span></dt></dl> <dl><dd></dd> <dt><a href="/blog/archives/" class="more">更多文章&gt;</a></dt></dl></div></div></main></div> <div class="footer"><div class="icons"><a href="mailto:894072666@qq.com" title="发邮件" target="_blank" class="iconfont icon-youjian"></a><a href="https://github.com/xugaoyi" title="GitHub" target="_blank" class="iconfont icon-github"></a><a href="https://music.163.com/#/playlist?id=755597173" title="听音乐" target="_blank" class="iconfont icon-erji"></a></div> 
  Theme by
  <a href="https://github.com/xugaoyi/vuepress-theme-vdoing" target="_blank" title="本站主题">Vdoing</a> 
    | Copyright © 2019-2022
    <span>Evan Xu | <a href="https://github.com/xugaoyi/vuepress-theme-vdoing/blob/master/LICENSE" target="_blank">MIT License</a></span></div> <div class="buttons"><div title="返回顶部" class="button blur go-to-top iconfont icon-fanhuidingbu" style="display:none;"></div> <div title="去评论" class="button blur go-to-comment iconfont icon-pinglun" style="display:none;"></div> <div title="主题模式" class="button blur theme-mode-but iconfont icon-zhuti"><ul class="select-box" style="display:none;"><li class="iconfont icon-zidong">
          跟随系统
        </li><li class="iconfont icon-rijianmoshi">
          浅色模式
        </li><li class="iconfont icon-yejianmoshi">
          深色模式
        </li><li class="iconfont icon-yuedu">
          阅读模式
        </li></ul></div></div> <!----> <!----> <!----></div><div class="global-ui"><div></div></div></div>
    <script src="/blog/assets/js/app.aaf1b95a.js" defer></script><script src="/blog/assets/js/2.4e88da26.js" defer></script><script src="/blog/assets/js/102.c6fb27ad.js" defer></script>
  </body>
</html>
